function x = custom_tinv(p, v)
% custom_tinv  - returns inverse CDF of the Student's t-distribution
%
% FORMAT:       x = custom_tinv(p, v);
%
% Input fields:
%
%       p           CDF of t distribution with v d.f. at points x
%       v           d.f. of distribution function
%
% Output fields:
%
%       x           t-variate (Student's t has range (-Inf,Inf))

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 2 || ...
   ~isnumeric(p) || ...
   ~isnumeric(v) || ...
    isempty(v) || ...
    any(isnan(p(:))) || ...
    any(isinf(v(:)) | isnan(v(:)) | v(:) < 0)
    error( ...
        'BVQXtools:BadArgument', ...
        'Missing or invalid argument given.' ...
    );
end
if isempty(p)
    x = [];
    return;
end
osize = size(p);
if numel(p) == 1 && ...
    numel(v) > 1
    osize = size(v);
end
if ~isa(p, 'double')
    p = double(p(:));
else
    p = p(:);
end
if ~isa(v, 'double')
    v = double(v(:));
else
    v = v(:);
end

% calculus
x = reshape((sign(p - 1/2) .* ...
    sqrt(v ./ custom_betainv(2 * min(p, 1-p), v ./ 2, 1/2) - v)), osize);
